package com.ptl.bp.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ptl.bp.config.ApiResult;
import com.ptl.bp.config.BizException;
import com.ptl.bp.service.PortableBatteryImportListener;
import com.ptl.bp.dto.PortableBatteryExportDTO;
import com.ptl.bp.dto.PortableBatteryImportDTO;
import com.ptl.bp.dto.PortableQo;
import com.ptl.bp.entity.PortableBatteryEntity;
import com.ptl.bp.service.PortableBatteryService;
import com.ptl.bp.util.ExcelUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequestMapping("/api/portableBattery")
@Tag(name = "便携式电池管理", description = "便携式电池的增删改查接口")
public class PortableBatteryController {

    @Resource
    private PortableBatteryService portableBatteryService;
    @Resource
    private ApplicationContext applicationContext;

    @PostMapping
    @Operation(summary = "创建便携式电池", description = "创建新的便携式电池记录")
    public ApiResult<PortableBatteryEntity> create(@Valid @RequestBody PortableBatteryEntity portableBatteryEntity) {
        portableBatteryService.add(portableBatteryEntity);
        return ApiResult.success(portableBatteryEntity);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "分页查询便携式电池列表")
    public ApiResult<IPage<PortableBatteryEntity>> getPage(Page<PortableBatteryEntity> page, PortableQo portableQo) {
        IPage<PortableBatteryEntity> result = portableBatteryService.getPage(page,portableQo, this);
        return ApiResult.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新便携式电池", description = "根据ID更新便携式电池记录")
    public ApiResult<PortableBatteryEntity> update(@PathVariable Long id,
                                                   @Valid @RequestBody PortableBatteryEntity portableBatteryEntity) {
        portableBatteryEntity.setId(id);
        portableBatteryService.updateById(portableBatteryEntity);
        log.info("更新便携式电池成功: {}", id);
        return ApiResult.success(portableBatteryEntity);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除便携式电池", description = "根据ID删除便携式电池记录")
    public ApiResult<String> delete(@PathVariable Long id) {
        portableBatteryService.removeById(id);
        log.info("删除便携式电池成功: {}", id);
        return ApiResult.success("");
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询", description = "根据ID查询便携式电池详情")
    public ApiResult<PortableBatteryEntity> getById(@PathVariable Long id) {
        PortableBatteryEntity battery = portableBatteryService.getById(id);
        return ApiResult.success(battery);
    }

    @Operation(summary = "导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response, @Parameter(description = "查询条件") PortableQo query) {
        ApiResult<IPage<PortableBatteryEntity>> res = this.getPage(Page.of(1, -1), query);
        if (res.getCode() != ApiResult.ResStatusEnum.SUCCESS || res.getData() == null) {
            throw new BizException("导出失败");
        }
        List<PortableBatteryExportDTO> dtos = res.getData().getRecords().stream().map(v -> {
            PortableBatteryExportDTO dto = new PortableBatteryExportDTO();
            BeanUtils.copyProperties(v, dto);
            return dto;
        }).collect(Collectors.toList());
        ExcelUtils.exportExcel(response, "便携式电池.xlsx", dtos, PortableBatteryExportDTO.class);
    }

    @Operation(summary = "下载模版")
    @GetMapping("/template")
    public void template(HttpServletResponse response) {
        ExcelUtils.exportExcel(response, "便携式电池-导入模版.xlsx", Collections.emptyList(), PortableBatteryImportDTO.class);
    }

    @Transactional
    @Operation(summary = "导入")
    @PostMapping("/import")
    public ApiResult<Object> importExcel(@RequestParam("file") MultipartFile file) {
        ExcelUtils.validExcelFile(file);
        PortableBatteryImportListener portableBatteryImportListener = applicationContext.getBean(PortableBatteryImportListener.class);

        try {
            EasyExcel.read(file.getInputStream(), PortableBatteryImportDTO.class, portableBatteryImportListener)
                    .sheet()
                    .headRowNumber(1)
                    .doRead();
        } catch (Exception e) {
            throw new RuntimeException("Excel文件读取失败: " + e.getMessage());
        }
        if (!portableBatteryImportListener.getErrorList().isEmpty()) {
            return ApiResult.fail("导入失败", portableBatteryImportListener.getErrorList());
        }
        return ApiResult.success("操作成功");
    }

}